package com.qf.homework.service.impl;

import com.qf.homework.dao.BookDao;
import com.qf.homework.entity.Book;
import com.qf.homework.service.BookService;
import org.junit.Test;
import utils.MybatisUtils;

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class BookServiceImpl implements BookService {
    private static BookDao dao = MybatisUtils.getMapper(BookDao.class);

    @Override
    public String getRandomChinese() {
        return String.valueOf((char) (0x4e00 + (int) (Math.random() * (0x9fa5 - 0x4e00 + 1))));
    }

    @Override
    public BufferedReader createFile() {
        final URL url = this.getClass().getClassLoader().getResource("file/bookFile.txt");
        BufferedWriter bw = null;
        BufferedReader br = null;
        try {
            final File file = new File(url.toURI());
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
            for (int i = 0; i < 500000; i++) {
                String name = getRandomChinese() + getRandomChinese() + getRandomChinese() + getRandomChinese();
                String author = getRandomChinese() + getRandomChinese() + getRandomChinese();
                String publish = getRandomChinese() + getRandomChinese() + getRandomChinese() + getRandomChinese() + "出版社";
                int sort = new Random().nextInt(3);
                String book = name + "," + author + "," + publish + "," + sort;
                bw.write(book);
                bw.newLine();
            }
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
            bw.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                bw.close();
                return br;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
